//课程相关的
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from '@/utils/http';
import { AxiosRes } from '@/utils/http';
import { RootState } from '../index';

//初始状态
const initialState = {
  //课程树结构
  subject_tree: [],
  //二级分类信息
  active_two: {
    title: '', //二级课程名称
    value: '', //二级课程id
  },
  topic_two_list: [], //
  active_topic: null, //
};

//创建一个切片
export const subjectSlice = createSlice({
  //设置切片的名字
  name: 'subject',
  initialState,
  //业务代码
  reducers: {
    set_subject_active_two: (state, action) => {
      //state:redux中公共状态信息,基于immer库,不需要自己克隆,可以直接修改数据
      //action:派发的行为对象,无需考虑行为标识,传递的其他信息,都是以action.payload的方式传递进来的值
      state.active_two = action.payload;
    },

    set_subject_active_topic: (state, action) => {
      state.active_topic = action.payload;
    },
  },

  //3 通过extraReducers 监听到get_subject_tree_async的fulfilled的状态
  extraReducers(builder) {
    builder
      //获取课程列表fulfilled
      .addCase(get_subject_tree_async.fulfilled, (state, res) => {
        //4 改state的值
        state.subject_tree = res.payload;
      })
      //获取题目列表的pending
      .addCase(get_topic_two_list.pending, (state, res) => {
        state.active_topic = res.payload;
      })
      //获取题目列表fulfilled
      .addCase(get_topic_two_list.fulfilled, (state, res) => {
        state.topic_two_list = res.payload;
      });
  },
});

//调接口
export const get_subject_tree_async = createAsyncThunk('get/subject_tree', async () => {
  const res: AxiosRes = await axios.get('/api/subject');
  return res.data.data;
});
export const get_topic_two_list: any = createAsyncThunk(
  'get/topic_two_list',
  async (action, state) => {
    console.log('action', action);
    console.log('state', state);
    const res: AxiosRes = await axios.get(`/api/topic/${action}`);
    return res.data.data;
  },
);

//导出的公共状态信息,可以在页面里面用useSelector接受获取公共状态的信息.
export const select_subject_tree = (state: RootState) => {
  return state.subject.subject_tree;
};

export const select_active_two = (state: RootState) => {
  return state.subject.active_two;
};
export const select_topic_two_list = (state: RootState) => {
  return state.subject.topic_two_list;
};
export const select_active_topic = (state: RootState) => {
  return state.subject.active_topic;
};

// 从切片中获取actionCreator:此处结构的方法和上线reducers中的方法,仅仅是函数名相同;执行方法,返回需要派发的行为对象,后期我们可以基于dispatch进行任务派发即可!!
export const { set_subject_active_two, set_subject_active_topic } = subjectSlice.actions;

export default subjectSlice.reducer;
